package com.bigfans.catalogservice.api;

import com.bigfans.catalogservice.model.*;
import com.bigfans.catalogservice.model.entity.SpecOptionEntity;
import com.bigfans.catalogservice.model.vo.SpecGroupVO;
import com.bigfans.catalogservice.model.vo.SpecOptionVO;
import com.bigfans.catalogservice.model.vo.SpecValueVO;
import com.bigfans.catalogservice.service.product.ProductService;
import com.bigfans.catalogservice.service.sku.SkuService;
import com.bigfans.catalogservice.service.sku.StockService;
import com.bigfans.catalogservice.service.spec.SpecOptionService;
import com.bigfans.catalogservice.service.spec.SpecService;
import com.bigfans.catalogservice.service.spec.SpecValueService;
import com.bigfans.framework.utils.CollectionUtils;
import com.bigfans.framework.web.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author lichong
 * @create 2015-05-30 下午10:56
 **/
@RestController
public class SkuApi {

    @Autowired
    private ProductService productService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private SpecOptionService specOptionService;
    @Autowired
    private SpecValueService specValueService;
    @Autowired
    private SpecService specService;
    @Autowired
    private StockService stockService;

    @GetMapping("/sku/{prodId}")
    public RestResponse getSku(@PathVariable(value = "prodId") String prodId) throws Exception {
        // 1. 获取当前商品组下所有sku
        List<SKU> skuList = skuService.listByProdId(prodId);
        if(CollectionUtils.isEmpty(skuList)){
            return RestResponse.ok();
        }
        SKU selectedSku = skuList.stream().filter(sku -> prodId.equals(sku.getProdId())).findFirst().get();
        // 保存每个选项下面的所有可选值
        Map<String , Set<String>> allOptValMaps = new HashMap<>();
        List<String> optionIdList = new ArrayList<>();
        List<String> valueIdList = new ArrayList<>();
        skuList.forEach((sku) -> {
            Map<String , String> skuMap = sku.getSkuMap();
            for (Map.Entry<String, String> entry : skuMap.entrySet()) {
                if (allOptValMaps.containsKey(entry.getKey())) {
                    allOptValMaps.get(entry.getKey()).add(entry.getValue());
                } else {
                    Set<String> vals = new HashSet<>();
                    vals.add(entry.getValue());
                    allOptValMaps.put(entry.getKey(), vals);
                    optionIdList.add(entry.getKey());
                }
                optionIdList.add(entry.getValue());
            }
        });

        List<SpecOption> specOptionList = specOptionService.listByIdList(optionIdList);
        List<SpecValue> specValueList = specValueService.listByIdList(valueIdList);
        Map<String , String> specOptionNameMap = specOptionList.stream().collect(Collectors.toMap(SpecOption::getId , SpecOption::getName));
        Map<String , String> specValueNameMap = specValueList.stream().collect(Collectors.toMap(SpecValue::getId , SpecValue::getValue));

        // 根据当前选中的商品计算出所有可选sku组合
        Map<String, String> selectedSkuMap = selectedSku.getSkuMap();
        List<SpecGroupVO> groupVOList = new ArrayList<>();
        for(Map.Entry<String , String> entry : selectedSkuMap.entrySet()){
            String selectedOpt = entry.getKey();
            String selectedVal = entry.getValue();
            SpecGroupVO group = new SpecGroupVO();
            group.setOption(specOptionNameMap.get(selectedOpt));

            Set<String> allValues = allOptValMaps.get(selectedOpt);
            for (String val : allValues) {
                Map<String , String> currentSkuMap = new HashMap<>(selectedSkuMap);
                currentSkuMap.put(selectedOpt , val);
                SKU availableSku = skuList.stream().filter((item) -> item.skuMapEquals(currentSkuMap)).findFirst().orElse(null);
                SpecValueVO valueVO = new SpecValueVO();
                valueVO.setValue(specValueNameMap.get(val));
                valueVO.setSelected(val.equals(selectedVal));
                if(availableSku != null){
                    valueVO.setSelectable(true);
                    valueVO.setOutOfStock(availableSku.outOfStock());
                    valueVO.setProdId(availableSku.getProdId());
                } else {
                    valueVO.setSelectable(false);
                }
                group.addValue(valueVO);
            }
            groupVOList.add(group);
        }

        SkuResult result = new SkuResult();
        result.setSpecGroups(groupVOList);
        return RestResponse.ok(result);
    }

    private List<String> combine(List<List<String>> lists) {
        List<String> heads = lists.get(0);
        for (int i = 1; i < lists.size(); i++) {
            List<String> result = new ArrayList<>();
            List<String> targets = lists.get(i);
            for (int j = 0; j < heads.size(); j++) {
                for (int k = 0; k < targets.size(); k++) {
                    result.add(heads.get(j) + ";" + targets.get(k));
                }
            }
            heads = result;
        }
        return heads;
    }
}
